package com.dili.dd.gpi.controller;

import com.dili.dd.gpi.domain.Application;
import com.dili.dd.gpi.service.DmaAppService;
import com.dili.dd.gpi.service.DmaDataService;
import com.dili.dd.gpi.util.Md5Util;
import com.dili.dd.gpi.util.spring.JsonView;
import com.dili.dd.gpi.util.spring.ObjectConvertAnno;
import com.diligrp.manage.sdk.domain.UserTicket;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 思思君 on 2015/10/14.
 */
@Controller
@RequestMapping("/dma/app")
public class DmaAppController
{
    private static final Logger LOGGER = LoggerFactory.getLogger(DmaAppController.class);

    @Resource
    private DmaAppService dmaAppService;

    @Resource
    private DmaDataService dmaDataService;

    @RequestMapping(value = "/html/list", method = RequestMethod.GET)
    public String toList(@ObjectConvertAnno UserTicket userTicket, Model model)
    {
        List<Application> applicationList = this.dmaAppService.getAppList(userTicket.getUserName());
        model.addAttribute("appList", applicationList);
        return "/WEB-INF/views/dma/app_list";
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public ModelAndView createApp(Application application, @ObjectConvertAnno UserTicket userTicket) throws ParseException
    {
        if (dmaAppService.getAppByName(application.getAppName()) != null)
        {
            return new ModelAndView(new JsonView(false, "应用名已经存在，无法创建应用！"));
        }

        setApplication(application, userTicket);
        Date curDate = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        application.setCreateDate(dateFormat.parse(dateFormat.format(curDate)));

        // 向hbase同步添加信息
        String userId = userTicket.getId().toString();
        String result = this.dmaDataService.insertUserAppkey(userId, application.getAppkey());
        try
        {
            Assert.isTrue("true".equals(result));
        }
        catch (Exception e)
        {
            LOGGER.error("insert user appkey error: " + e);
            return new ModelAndView(new JsonView(false, "应用创建失败：" + e.toString()));
        }

        if (dmaAppService.createApplyApp(application) == 1)
        {
            return new ModelAndView(new JsonView(true,"应用添加成功，appkey为：" + application.getAppkey()));
        }
        else
        {
            return new ModelAndView(new JsonView(false, "应用创建失败！"));
        }
    }

    @RequestMapping(value = "/html/create", method = RequestMethod.GET)
    public String toCreateHtml()
    {
        return "/WEB-INF/views/dma/app_add";
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ModelAndView updateApp(Application application, @ObjectConvertAnno UserTicket userTicket)
    {
        setApplication(application, userTicket);
        if (this.dmaAppService.updateApp(application) == 1)
        {
            return new ModelAndView(new JsonView(true, "更新成功！"));
        }
        else
        {
            return new ModelAndView(new JsonView(false, "更新失败！"));
        }
    }

    @RequestMapping(value = "/html/update", method = RequestMethod.GET)
    public String toUpdateHtml(String appId, Model model)
    {
        Application application = this.dmaAppService.getAppById(appId);
        model.addAttribute("application", application);
        return "/WEB-INF/views/dma/app_edit";
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public ModelAndView deleteApp(String appId, @ObjectConvertAnno UserTicket userTicket) throws Exception
    {
        try
        {
            // 在hbase中同步删除应用信息
            String userId = userTicket.getId().toString();
            String appkey = this.dmaAppService.getAppById(appId).getAppkey();
            String result = this.dmaDataService.deleteUserAppkey(userId, appkey);
            Assert.isTrue("true".equals(result));

            Map<String,Object> model = new HashMap<>();
            if (this.dmaAppService.deleteApp(appId) == 1)
            {
                return new ModelAndView(new JsonView(true, "删除成功！"));
            }
            else
            {
                return new ModelAndView(new JsonView(false, "删除失败！"));
            }
        }
        catch (Exception e)
        {
            LOGGER.error("delete app error: " + e);
            return new ModelAndView(new JsonView(false, "删除失败：" + e.toString()));
        }
    }

    private void setApplication(Application application, UserTicket userTicket)
    {
        application.setAppkey(generalAppkey(userTicket.getUserName(), application.getAppName()));
        application.setUsername(userTicket.getUserName());
    }

    private String generalAppkey(String username, String appName)
    {
        String appkey = Md5Util.generalAppKey(username, appName);

        List<Application> allAppList = dmaAppService.getAllAppList();
        int index = 1;
        while (StringUtils.isEmpty(appkey) || isAppkeyExist(appkey, allAppList))
        {
            if (index < 6)
            {
                String tempAppName = appName + index;
                appkey = Md5Util.generalAppKey(username, tempAppName);
                index++;
            }
            else
            {
                appkey = "";
                break;
            }
        }

        return appkey;
    }

    private boolean isAppkeyExist(String appkey, List<Application> allAppList)
    {
        for (Application app : allAppList)
        {
            if (app.getAppkey().equals(appkey))
            {
                return true;
            }
        }
        return false;
    }
}
